#include "captchaassistdialog.h"
#include "libs/controls/loadingframe.h"
#include <QCloseEvent>
#include <QMessageBox>
#include <QPushButton>
#include <QVBoxLayout>

CaptchaAssistDialog::CaptchaAssistDialog(QWidget* widget, QWidget* parent)
    : QDialog { parent, Qt::MSWindowsFixedSizeDialogHint }
{
    setWindowTitle(tr("Captcha Assist"));

    widget_parent_ = widget->parentWidget();
    widget_ = widget;
    widget_geometry_ = widget->geometry();

    QVBoxLayout* vl = new QVBoxLayout(this);
    vl->setContentsMargins(0, 0, 0, 0);
    vl->setSpacing(0);

    vl->addWidget(widget, 1);

    QHBoxLayout* hl = new QHBoxLayout;
    hl->setContentsMargins(4, 4, 4, 4);
    vl->addLayout(hl);

    QPushButton* close_button = new QPushButton(tr("Close"), this);
    hl->addWidget(close_button, 1);

    loading_frame_ = new yc::LoadingFrame(tr("Waiting for captcha..."), this);
    loading_frame_->hide();

    connect(close_button, &QPushButton::clicked, this, &CaptchaAssistDialog::close);
}

CaptchaAssistDialog::~CaptchaAssistDialog()
{
    if (widget_) {
        widget_->setParent(widget_parent_);
        widget_->setGeometry(widget_geometry_);
        widget_->show();
        widget_ = nullptr;
    }
}

void CaptchaAssistDialog::showLoading()
{
    loading_frame_->show();
    loading_frame_->raise();
}

void CaptchaAssistDialog::hideLoading()
{
    loading_frame_->hide();
}

void CaptchaAssistDialog::resizeEvent(QResizeEvent* event)
{
    QDialog::resizeEvent(event);

    loading_frame_->resize(event->size().width(), event->size().height() - 42);
    loading_frame_->raise();
}

void CaptchaAssistDialog::closeEvent(QCloseEvent* event)
{
    auto ret = QMessageBox::warning(this, tr("Captcha Assist"),
                                    tr("Are you sure to give up the captcha assist?"),
                                    QMessageBox::Ok | QMessageBox::Cancel, QMessageBox::Ok);
    if (ret == QMessageBox::Ok) {
        if (widget_) {
            widget_->setParent(widget_parent_);
            widget_->setGeometry(widget_geometry_);
            widget_->show();
            widget_ = nullptr;
        }
        Q_EMIT discarded();
        reject();
        event->accept();
    } else {
        event->ignore();
    }
}
